import { RegExp } from 'core-js'
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: null, // 登录token
    icon: null, // 用户头像
    nickName: null, // 用户昵称
    userID: null, // 用户id
    toLogin: false, // 登录组件切换
    cookieKeys: ["token", "icon", "nickName", "userID"] // 需要存储在cookie中的数据
  },
  mutations: {
    // 登录组件切换
    loginSwitch(state) {
      state.toLogin = !state.toLogin;
    },
    // cookie切割
    splitCookie(state) {
      let cookie = document.cookie
      if (cookie.indexOf("token") === -1 ) return 
      state.cookieKeys.forEach( item => {
        let key = item
        let reg = new RegExp(`(^|\\s)${key}=([^;]+)`)
        state[item] = cookie.match(reg)[2]
      })
    },
    // cookie清空
    removeCookie(state) {
      let date = new Date( new Date().getTime() - 10000 );
      state.cookieKeys.forEach( item => {
        state[item] = ""
        document.cookie = `${item} = ""; expires = ${date.toUTCString()}`
      })
    }
  },
  actions: {
  },
  modules: {
  }
})
